<script setup lang="ts">
  import { ref, watch, reactive, onMounted, computed } from 'vue';
  import { Notification } from '@arco-design/web-vue';
  import {
    queryAo,
    searchAoBillById,
    searchAoMatchById,
    searchHandleMatchInfo,
    handleMatch,
    remmoveMatchInfo,
  } from '@/api/sorting-matching';

  const columns: any[] = [
    {
      title: 'AO列表',
      align: 'left',
      headerCellStyle: { fontSize: 'large', fontWeight: 400 },
      children: [
        {
          title: '序号',
          dataIndex: 'rowId',
          key: 'rowId',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 80,
        },
        {
          title: '分拣状态',
          dataIndex: 'sortingStatusName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '缺件状态',
          dataIndex: 'stateName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: 'AO号',
          dataIndex: 'aoCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: 'AO名称',
          dataIndex: 'aoName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '站位',
          dataIndex: 'station',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '架次',
          dataIndex: 'planeNo',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '工作包编号',
          dataIndex: 'packageCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '单位',
          dataIndex: 'shop',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 80,
        },
        {
          title: '配送状态',
          dataIndex: 'delieveryStateName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '缺件状态',
          dataIndex: 'aStateName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
      ],
    },
  ];
  // 物料清单
  const columnsTwo: any[] = [
    {
      title: '物料清单',
      align: 'left',
      headerCellStyle: { fontSize: 'large', fontWeight: 400 },
      children: [
        {
          title: '图号',
          dataIndex: 'itemCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '需求数量',
          dataIndex: 'itemQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '配套数量',
          dataIndex: 'matchQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '装配图号',
          dataIndex: 'repartAss',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '操作',
          dataIndex: 'action',
          slotName: 'action',
          fixed: 'right',
          width: 120,
        },
      ],
    },
  ];
  // 配套清单
  const columnsThree: any[] = [
    {
      title: '配套清单',
      align: 'left',
      headerCellStyle: { fontSize: 'large', fontWeight: 400 },
      children: [
        {
          title: '分拣状态',
          dataIndex: 'isSortName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '配套状态',
          dataIndex: 'stateName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '图号',
          dataIndex: 'itemCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '质量编号',
          dataIndex: 'qualityCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '分拣数量',
          dataIndex: 'packageCount',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '需求数量',
          dataIndex: 'itemQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '分配数量',
          dataIndex: 'matchQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 120,
        },
        {
          title: '装配图号',
          dataIndex: 'repartAss',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
          width: 180,
        },
        {
          title: '操作',
          dataIndex: 'action',
          slotName: 'action',
          fixed: 'right',
          width: 120,
        },
      ],
    },
  ];
  // 配套信息
  const columnsFour: any[] = [
    {
      title: '配套信息',
      align: 'left',
      headerCellStyle: { fontSize: 'large', fontWeight: 400 },
      children: [
        {
          title: '图号',
          dataIndex: 'itemCode',
        },
        {
          title: '质量编号',
          dataIndex: 'qualityCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '需求数量',
          dataIndex: 'itemQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '配套数量',
          dataIndex: 'matchQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '状态',
          dataIndex: 'stateName',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '手动配套标识',
          dataIndex: 'addTypeName',
        },
        {
          title: '装配图号',
          dataIndex: 'repartAss',
        },
        {
          title: '缓存箱',
          dataIndex: 'workbinCode',
        },
      ],
    },
  ];
  // 库存
  const columnsFive: any[] = [
    {
      title: '库存',
      align: 'left',
      headerCellStyle: { fontSize: 'large', fontWeight: 400 },
      children: [
        {
          title: '操作',
          dataIndex: 'action',
          slotName: 'action',
          fixed: 'left',
        },
        {
          title: 'AO号',
          dataIndex: 'aoCode',
        },
        {
          title: '图号',
          dataIndex: 'itemCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '质量编号',
          dataIndex: 'qualityCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '型号',
          dataIndex: 'mProductNumber',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '台账数量',
          dataIndex: 'itemQty',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '合格证号',
          dataIndex: 'mesCheckQualiticationId',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
        {
          title: '缓存箱',
          dataIndex: 'workbinCode',
          sortable: {
            sortDirections: ['ascend', 'descend'],
          },
        },
      ],
    },
  ];
  // 创建一个响应式的本地副本
  const localTableData = ref<any>();
  const tableDataTwo = ref<any[]>([]);
  const tableDataThree = ref<any[]>([]);
  const showDrawer = ref<boolean>(false);
  const visible = ref<boolean>(false);
  // 数据库一共有多少条
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(30);
  const formValues = reactive({
    packageCode: '',
    aoCode: '',
    astate: '',
    planeNo: '',
    sortingStatus: '',
    delieveryState: '',
    size: computed(() => pageSize.value),
    current: computed(() => pageNum.value),
  });
  async function handleSearch() {
    const response = await queryAo(formValues);
    if (response.retCode === '200') {
      // Notification.success({
      //   title: '成功',
      //   content: '查询成功',
      //   closable: true,
      // });
      localTableData.value = response.responseBody?.records;
      total.value = response.responseBody?.total;
    } else {
      Notification.error({
        title: '失败',
        content: response.message,
        closable: true,
      });
    }
  }
  function reset() {
    // 如果你想重置 formValues 的其他属性

    Object.keys(formValues).forEach((key) => {
      if (key !== 'size' && key !== 'current') {
        (formValues as Record<string, any>)[key] = ''; // 只重置其他属性
      }
    });

    pageNum.value = 1;
    pageSize.value = 10;
    setTimeout(() => {
      handleSearch();
    }, 150);
  }
  // 查询物料清单和配套清单
  async function getList(info: any) {
    const res = await searchAoBillById(info);
    tableDataTwo.value = res.responseBody;
    const data = await searchAoMatchById(info);
    tableDataThree.value = data.responseBody;
  }
  const listInfo = ref();
  // 查看配套信息
  async function showList(record: any) {
    listInfo.value = record;
    getList(listInfo.value);
  }

  const tabArr = ref<any>();
  // 重新配套
  async function add(record: any) {
    record.shop = listInfo.value.shop;
    const data = await searchHandleMatchInfo(record);
    tabArr.value = data;
    showDrawer.value = true;
  }
  const row = ref<any>();
  // 添加配套
  function addMath(record: any) {
    row.value = record;
    visible.value = true;
  }
  const num = ref<string>('');
  // 确认新增
  async function handleOk() {
    if (!/^\d+$/.test(num.value)) {
      // 如果不是只包含数字
      Notification.warning({
        title: '提示',
        content: '请输入有效的数字',
        closable: true,
      });
      return;
    }
    const match: any = row.value;
    match.matchQty = num.value;
    match.msAoMatchBillId = tabArr.value.billInfo.msAoMatchBillId;
    match.packageCode = tabArr.value.billInfo.packageCode;
    match.aoCode = tabArr.value.billInfo.aoCode;
    match.productCode = tabArr.value.billInfo.productCode;
    match.batchNo = tabArr.value.billInfo.batchNo;
    match.planeNo = tabArr.value.billInfo.planeNo;
    const data: any = await handleMatch(match);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
    showDrawer.value = false;
    // 更新数据
    getList(listInfo.value);
  }

  // 删除配套
  async function onDel(record: any) {
    try {
      const data: any = await remmoveMatchInfo(record);
      // console.log(data);
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (e) {
      Notification.error({
        title: '失败',
        content: '网络异常超时',
        closable: true,
      });
    } finally {
      getList(listInfo.value);
    }
  }

  // 监听页面变化
  watch([pageNum, pageSize], () => {
    handleSearch();
  });
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
  //
  function afterVisibleChange(val: any) {
    if (!val) {
      showDrawer.value = val;
    }
  }
  onMounted(() => {
    handleSearch();
  });
</script>

<template>
  <div class="content-page">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input
          v-model="formValues.aoCode"
          placeholder="AO编号"
          size="large"
          allow-clear
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.packageCode"
          placeholder="工作包号"
          size="large"
          allow-clear
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.planeNo"
          placeholder="架次"
          size="large"
          allow-clear
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-select
          v-model="formValues.sortingStatus"
          placeholder="分拣状态"
          default-value=""
          allow-clear
          @press-enter="handleSearch"
        >
          <a-option value="00"> 未分拣</a-option>
          <a-option value="02"> 分拣完成</a-option>
          <a-option value="04"> 工艺更改</a-option>
          <a-option value="08"> 初始状态</a-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <a-select
          v-model="formValues.astate"
          placeholder="缺件状态"
          default-value=""
          allow-clear
          @press-enter="handleSearch"
        >
          <a-option value="00"> 未缺件</a-option>
          <a-option value="A"> A类缺件</a-option>
          <a-option value="B"> B类缺件</a-option>
          <a-option value="C"> 缺件完成</a-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <a-select
          v-model="formValues.delieveryState"
          placeholder="配送状态"
          default-value=""
          allow-clear
          @press-enter="handleSearch"
        >
          <a-option value="00">未配送 </a-option>
          <a-option value="02">部分配送</a-option>
          <a-option value="04">部分完成</a-option>
        </a-select>
      </a-col>
      <a-col :span="12">
        <a-space>
          <a-button type="primary" size="large" @click="handleSearch">
            查询
          </a-button>
          <a-button class="btn-reset" size="large" @click="reset"
            >重置</a-button
          >
        </a-space>
      </a-col>
    </a-row>

    <a-divider style="margin-top: 4px; margin-bottom: 4px" />
    <div>
      <a-table
        :stripe="true"
        class="top-table"
        :pagination="false"
        :columns="columns"
        :data="localTableData"
        :scroll="{ y: 400 }"
        style="height: 250px"
        @row-click="showList"
      >
      </a-table>
      <div class="page-position">
        <a-pagination
          :total="total"
          :current="pageNum"
          :page-size="pageSize"
          show-total
          show-jumper
          show-page-size
          :page-size-options="[30, 50, 100, 500]"
          @change="change"
          @update:page-size="changeSize"
        />
      </div>
    </div>

    <a-row class="margin-top" :gutter="10">
      <a-col :span="12">
        <a-table
          :stripe="true"
          class="top-table"
          :columns="columnsTwo"
          :data="tableDataThree"
          :scroll="{ y: 400 }"
          style="height: 350px"
        >
          <template #action="{ record }">
            <a-button type="primary" @click="add(record)">添加配套</a-button>
          </template>
        </a-table>
      </a-col>
      <a-col :span="12">
        <a-table
          :stripe="true"
          class="top-table"
          :columns="columnsThree"
          :data="tableDataTwo"
          :scroll="{ y: 400 }"
          style="height: 350px"
        >
          <template #action="{ record }">
            <a-popconfirm
              content="确定删除吗?"
              ok-text="确认"
              cancel-text="取消"
              @ok="onDel(record)"
            >
              <a-button type="text" class="font-color">删除配套</a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-col>
    </a-row>
  </div>
  <a-drawer
    :width="1000"
    :height="340"
    :visible="showDrawer"
    placement="right"
    :footer="false"
    @after-visible-change="afterVisibleChange"
    @cancel="showDrawer = false"
  >
    <template #title> 手动配套 </template>
    <a-row>
      <a-col :span="6">AO号：{{ tabArr?.billInfo?.aoCode }}</a-col>
      <a-col :span="6">图号：{{ tabArr?.billInfo?.itemCode }}</a-col>
      <a-col :span="6">图号名称：{{ tabArr?.billInfo?.itemName }}</a-col>
      <a-col :span="6">装配图号：{{ tabArr?.billInfo?.repartAss }}</a-col>
    </a-row>
    <a-row class="margin-top">
      <a-col :span="6">需求数量：{{ tabArr?.billInfo?.itemQty }}</a-col>
      <a-col :span="6">状态名称：{{ tabArr?.billInfo?.stateName }}</a-col>
      <a-col :span="6">分厂：{{ tabArr?.billInfo?.shop }}</a-col>
    </a-row>
    <a-row class="margin-top" :gutter="10">
      <!-- 配套信息 -->
      <a-col :span="8">
        <a-table
          :stripe="true"
          class="top-table"
          :columns="columnsFour"
          :data="tabArr?.matchInfos"
        >
        </a-table>
      </a-col>

      <a-col :span="16">
        <!-- 库存 -->
        <a-table
          :stripe="true"
          class="top-table"
          :columns="columnsFive"
          :data="tabArr?.workbins"
        >
          <template #action="{ record }">
            <a-button type="primary" @click="addMath(record)"
              >添加配套</a-button
            >
          </template>
        </a-table>
      </a-col>
    </a-row>
    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="visible = false">
      <template #title> 提示 </template>
      <a-input v-model="num" placeholder="请输入配套数量" size="large" />
    </a-modal>
  </a-drawer>
</template>

<style scoped>
  span {
    margin-bottom: 16px;
  }
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .content-page {
    padding-left: 12px;
    padding-right: 12px;
  }
  .ao-list-title {
    background-color: azure;
    font-size: large;
    font-weight: 400;
  }
  .margin-top {
    margin-top: 10px;
  }
</style>
